package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import cn.tedu._03vehicle.mapper.UserMapper;
import cn.tedu._03vehicle.pojo.dto.UserLoginParam;
import cn.tedu._03vehicle.pojo.dto.UserRegParam;
import cn.tedu._03vehicle.pojo.entity.User;
import cn.tedu._03vehicle.pojo.vo.UserLoginVO;
import cn.tedu._03vehicle.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "用户管理")
@Slf4j
@RestController
@RequestMapping("v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("reg")
    @Operation(summary = "用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody @Validated UserRegParam userRegParam){
        log.debug("userRegParam="+ userRegParam);
        String username = userRegParam.getUsername();
        int count = userMapper.selectByUsername(username);
        if (count>0){//  用户名被占用
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }
        //用户未被占用
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.addUser(user);
        return JsonResult.ok();
    }
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 20)
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("userLoginPrarm="+ userLoginParam);
        UserLoginVO userLoginVO = userMapper.login(userLoginParam);
        if (userLoginVO!= null){
            //  登录成功
            session.setAttribute("user",userLoginVO);
            return JsonResult.ok(userLoginVO);
        }
        //  登录失败
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR, userLoginParam);
    }
    @GetMapping("currentUser")
    @Operation(summary = "获取当前登录用户信息")
    @ApiOperationSupport(order = 30)
    public JsonResult getCurrentUser(HttpSession session){
        UserLoginVO user = (UserLoginVO) session.getAttribute("user");
        if (user==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        List<UserVO> list = userMapper.getCurrentUser();
        return JsonResult.ok(list);


    }
    @GetMapping("logout")
    @Operation(summary = "退出登录")
    @ApiOperationSupport(order = 40)
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
